package site.jlopen.assets.shiro.filter;


import java.io.IOException;
import java.io.PrintWriter;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson2.JSON;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import site.jlopen.assets.shiro.token.JwtToken;
import site.jlopen.entity.BaseResponse;
import site.jlopen.utils.jwt.JwtTool;
 
/**
 * @Description 自定义过滤器
 * @Date 2021/8/18
 **/
public class ApiAuthenticationFilter extends AuthenticatingFilter {
 
    private static final Logger log = LoggerFactory.getLogger(ApiAuthenticationFilter.class);
 
 
    /**
     * 拦截校验  没有登录的情况下会走此方法
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        String token = request.getHeader("token");
 
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,PUT,DELETE,UPDATE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
 
        Subject subject = getSubject(servletRequest,servletResponse);
 
        if (!subject.isAuthenticated()){
        	String url = request.getRequestURI();
        	if("/api/auth".equals(url)) {
        		return true;
        	}
            // 未登录
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(new BaseResponse<String>(401, "鉴权失败:未登录")));
            return false;
        }
 
        if (StringUtils.isEmpty(token)){
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(new BaseResponse<String>(401, "鉴权失败")));
            return false;
        }else {
        	boolean checkToken = JwtTool.verify(token);
        	if(!checkToken) {
        		PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(new BaseResponse<String>(401, "鉴权失败")));
                return false;
        	}
            return executeLogin(servletRequest, servletResponse);
        }
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        if (token == null){
            return null;
        }
        return new JwtToken(token);
    }
    
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        Throwable throwable = e.getCause() == null ? e : e.getCause();
        String json = JSON.toJSONString(new BaseResponse<String>(500, e.getMessage()));
        try {
            httpServletResponse.getWriter().print(json);
        } catch (IOException ioException) {
            log.error("认证授权异常：{}", throwable);
        }
        return false;
    }
 
    /**
     * 跨域支持
     * @param servletRequest
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest servletRequest, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(servletRequest);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
            httpResponse.setHeader("Access-Control-Allow-Methods", "GET,PUT,DELETE,UPDATE,OPTIONS");
            httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
 
            System.out.println(httpRequest.getHeader("Origin"));
            System.out.println(httpRequest.getMethod());
            System.out.println(httpRequest.getHeader("Access-Control-Request-Headers"));
            httpResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        if (token != null && !"".equals(token)) {
            try {
                JwtToken jwtToken = new JwtToken(token);
                Subject subject = SecurityUtils.getSubject();
                subject.login(jwtToken);
                return true;
            } catch (UnknownAccountException e) {
                log.error("token失效，请重新登录:{}", e);
               response.getWriter().print(JSON.toJSONString(new BaseResponse<String>(401, "鉴权失败")));
            } catch (Exception e) {
                log.error("token失效，请重新登录:{}", e);
               response.getWriter().print(JSON.toJSONString(new BaseResponse<String>(401, "鉴权失败")));
            }
            return false;
        }else {
            // session方式
            return super.preHandle(servletRequest, response);
        }
    }
 
/*    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        HttpServletResponse httpResponse = WebUtils.toHttp(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
            httpResponse.setHeader("Access-Control-Allow-Methods", "GET,PUT,DELETE,UPDATE,OPTIONS");
            httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
 
            System.out.println(httpRequest.getHeader("Origin"));
            System.out.println(httpRequest.getMethod());
            System.out.println(httpRequest.getHeader("Access-Control-Request-Headers"));
            httpResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }*/
 
}